<template>
  <view class="equity_add">
    <u-form ref="uForm" :errorType="errorType" :model="form" label-align="left" label-width="180">
      <view class="list">
        <view class="f-c-sb title">
          <view class="title_text">基础信息</view>
        </view>
        <view>
          <u-form-item :required="true" label="活动标题" prop="luckdrawTitle">
            <u-input v-model="form.luckdrawTitle" input-align="right" placeholder="请输入名称"/>
          </u-form-item>
          <u-form-item :required="true" label="活动开始时间" prop="timeStart">
            <view
                :style="'text-align: right;' + (!form.timeStart ? 'color:#ccc' : '')"
                @click="
								dateShow = true;
								timeType = 0;
							"
            >
              {{ form.timeStart || '请选择开始时间' }}
            </view>
          </u-form-item>
          <u-form-item :required="true" label="活动结束时间" prop="timeStart">
            <view
                :style="'text-align: right;' + (!form.timeEnd ? 'color:#ccc' : '')"
                @click="
								dateShow = true;
								timeType = 1;
							"
            >
              {{ form.timeEnd || '请选择结束时间' }}
            </view>
          </u-form-item>
          <u-form-item label="虚拟参加人数">
            <u-input v-model="form.inventedJoinNumber" input-align="right" placeholder="请输入纯数字" type="number"/>
          </u-form-item>
          <!-- <u-form-item :required="true" label="活动门店" prop='useStores'>
            <u-radio-group v-model="storeType">
              <u-radio
                @change="radioChange"
                name="0"
                active-color='#007FFF'
              >
                当前门店
              </u-radio>
              <u-radio
                @change="radioChange"
                name="1"
                active-color='#007FFF'
              >
                {{(storeType == 1 && form.useStores.split(',').length > 0) ? '已选择' + form.useStores.split(',').length + '家门店' : '选择其他门店'}}
							</u-radio>
						</u-radio-group>
					</u-form-item> -->
          <u-form-item label="使用门店" required>
            <u-radio-group v-model="storeType">
              <u-radio active-color="#007FFF" name="0" @change="radioChange">当前门店</u-radio>
              <u-radio active-color="#007FFF" name="1" @change="radioChange">选择其他门店</u-radio>
            </u-radio-group>
          </u-form-item>
          <u-form-item v-if="storeType == 1" :label-position="labelPosition" label="选择门店" label-width="150"
                       prop="useStores" required>
            <view v-if="form.useStores.split(',').length && form.useStores.length != 0 && selectStore.length == 0"
                  style="width: 100%;" @click="goselectStore">
              已选择{{ form.useStores.split(',').length }}家门店
            </view>
            <view v-else-if="selectStore.length != 0" style="width: 100%;" @click="goselectStore">
              已选择{{ selectStore.length }}家门店
            </view>
            <view v-else style="width: 100%;" @click="goselectStore">请选择门店</view>
          </u-form-item>
          <u-form-item :required="true" label="抽奖次数" prop="drawNumber">
            <view class="f-c" style="flex-direction:row-reverse;color:#ccc;">
              /次
              <u-input v-model="form.drawNumber" :rows="2" placeholder=" " resize="none"
                       style="padding:0 10rpx;width:80rpx;" type="digit"></u-input>
              每个用户总共能免费抽
            </view>
          </u-form-item>
          <u-form-item :required="true" label="抽奖设置" prop="drawLimit">
            <u-radio-group v-model="form.drawLimit">
              <u-radio active-color="#007FFF" name="1" shape="square">无限制</u-radio>
              <u-radio active-color="#007FFF" name="2" shape="square">仅能对新用户</u-radio>
            </u-radio-group>
          </u-form-item>
          <u-form-item :required="true" label="积分抽奖" prop="drawIntegral">
            <u-radio-group v-model="integralSet">
              <u-radio active-color="#007FFF" name="0" shape="square" @change="integralSetFun">无</u-radio>
              <u-radio active-color="#007FFF" name="1" shape="square" @change="integralSetFun">
                <view class="f-c">
                  每次消耗
                  <u-input
                      v-model="form.drawIntegral"
                      :rows="2"
                      :clearable="false"
                      :disabled="integralSet == '0'"
                      resize="none"
                      height="20"
                      placeholder=" "
                      style="margin:0 20rpx;width: 60rpx;"
                      type="digit"
                  ></u-input>
                  /积分
                </view>
              </u-radio>
            </u-radio-group>
          </u-form-item>
        </view>
      </view>
      <view class="list">
        <view class="f-c-sb title">
          <view class="title_text">活动信息</view>
        </view>
        <u-form-item :required="true" label="活动封面" label-position="top" prop="coverImage">
          <view class="remark">支持格式jpg/png，宽高比为4:3，仅限一张图片</view>
          <view @click="updatatype = 1">
            <u-upload
                :action="action"
                :file-list="fileList"
                :max-size="5 * 1024 * 1024"
                auto-upload
                data-type="activity"
                deletable
                max-count="1"
                name="files"
                @on-success="onSuccess"
            ></u-upload>
          </view>
        </u-form-item>
        <u-form-item :required="true" label="分享封面" label-position="top" prop="shareImage">
          <view class="remark">支持格式jpg/png，宽高比为5:4，仅限一张图片</view>
          <view @click="updatatype = 2">
            <u-upload
                :action="action"
                :file-list="fileList1"
                :max-size="5 * 1024 * 1024"
                auto-upload
                data-type="share"
                deletable
                max-count="1"
                name="files"
                @on-success="onSuccess"
            ></u-upload>
          </view>
        </u-form-item>
        <u-form-item :required="true" label="活动内容" label-position="top" prop="drawRule">
          <!-- <view class="f-c"> -->
          <!--            <view style="flex:1;text-align: right;color:#ccc;" @click="modal = true">{{
              form.drawRule || '请输入活动内容'
          }}
        </view>
        <u-icon name="arrow-right"></u-icon> -->
          <u-input v-model="form.drawRule" :auto-height="useNoticeTxt.autoHeight" :height="useNoticeTxt.height"
                   :type="useNoticeTxt.type" placeholder="请输入活动内容"/>
          <!-- </view> -->
        </u-form-item>
      </view>
      <view class="list">
        <view class="f-c-sb title">
          <view class="title_text">奖品</view>
        </view>
        <u-form-item :required="true">
          <view class="f-c">
            <view>添加奖品</view>
            <view style="font-size:20rpx;color:#C0C4CB;flex:1;">（最多支持设置5个奖品，1个用户仅能中奖1次）</view>
            <view style="color:#007AFF" @click="addLuckdrawGsDtos">
              <u-icon color="#007FFF" name="plus" size="40"></u-icon>
            </view>
          </view>
        </u-form-item>
        <view v-for="(item, index) in form.luckdrawGsDtos" :key="index">
          <view class="f-c-sb coupon_title">
            <view v-if="index != 0">奖品{{ index }}</view>
            <view v-if="index == 0"></view>
            <u-icon name="trash-fill" size="40" @click="delLuckdrawGsDtos(index)"></u-icon>
          </view>
          <u-form-item :required="true" label="奖品名称">
            <u-input v-model="item.prizeName" input-align="right" placeholder="请输入奖品名称"/>
          </u-form-item>
          <u-form-item :required="true" label="奖品类型">
            <view class="f-c-sb" @click="opentype(index)">
              <view v-if="!prizeTypeText[index]" style="color:#007FFF;text-align: right;flex:1;">请选择将奖品类型</view>
              <view v-if="prizeTypeText[index]" style="text-align: right;flex:1;">{{ prizeTypeText[index] }}</view>
              <u-icon name="arrow-right"></u-icon>
            </view>
          </u-form-item>
          <u-form-item v-if="item.prizeType == 2" :required="true" label="选择优惠券">
            <view class="f-c-sb" @click="selcoupon(index)">
              <view v-if="!item.couponName" style="color:#007FFF;text-align: right;flex:1;">请选择优惠券</view>
              <view v-if="item.couponName" style="color:#007FFF;text-align: right;flex:1;">{{ item.couponName }}</view>
              <u-icon name="arrow-right"></u-icon>
            </view>
          </u-form-item>
          <u-form-item :required="true" label="奖品发放库存">
			<u-input v-if='index == 0' :focus='focus0' v-model="item.prizeNumber" input-align="right" :placeholder="item.sendReceive?'优惠券剩余'+item.sendReceive : '请输入奖品库存数/份'" type="number"/>
			<u-input v-if='index == 1' :focus='focus1' v-model="item.prizeNumber" input-align="right" :placeholder="item.sendReceive?'优惠券剩余'+item.sendReceive : '请输入奖品库存数/份'" type="number"/>
			<u-input v-if='index == 2' :focus='focus2' v-model="item.prizeNumber" input-align="right" :placeholder="item.sendReceive?'优惠券剩余'+item.sendReceive : '请输入奖品库存数/份'" type="number"/>
			<u-input v-if='index == 3' :focus='focus3' v-model="item.prizeNumber" input-align="right" :placeholder="item.sendReceive?'优惠券剩余'+item.sendReceive : '请输入奖品库存数/份'" type="number"/>
			<u-input v-if='index == 4' :focus='focus4' v-model="item.prizeNumber" input-align="right" :placeholder="item.sendReceive?'优惠券剩余'+item.sendReceive : '请输入奖品库存数/份'" type="number"/>
          </u-form-item>
          <u-form-item :required="true" label="中奖概率">
            <!-- <u-input type='number' v-model="item.prizeProbability"/> -->
            <u-number-box v-model="item.prizeProbability" :max="1" :mix="0" :positive-integer="false"
                          :step="0.1"></u-number-box>
          </u-form-item>
          <view style="font-size:24rpx;color:#ccc;">可支持小数点后一位，剩余可分配概率{{ surplus_prob }}%</view>
        </view>
      </view>
    </u-form>
    <view class="f-c-sa btn">
      <u-button plain ripple size="medium" type="primary" @click="godetail">预览效果</u-button>
      <u-button ripple size="medium" type="primary" @click="submit">完成编辑</u-button>
    </view>
    <u-modal ref="uModal" v-model="modal" title="请输入活动说明" @cancel="cancelmodal">
      <view style="margin: 34rpx;">
        <u-input v-model="form.drawRule" :rows="2" resize="none" type="textarea"></u-input>
      </view>
    </u-modal>
    <u-select v-model="typeShow" :list="typeList" @confirm="selTprizeTpe"></u-select>
    <u-picker v-model="dateShow" :params="params" mode="time" placeholder="请选择时间" @confirm="dateChange"></u-picker>
    <u-toast ref="uToast"/>
  </view>
</template>

<script>
import {lotteryEdit, lotteryEditEcho} from '@/api/marketing.js';
import {mapGetters} from 'vuex';

export default {
  name: 'lottery_add',
  data() {
    return {
		focus0:false,
		focus1:false,
		focus2:false,
		focus3:false,
		focus4:false,
      fileList: [],
      fileList1: [],
      storeType: '0',
      params: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false
      },
      typeShow: false,
      modal: false,
      action: 'https://sj.shopec.com.cn/hty-manage-api/upload/files',
      updatatype: 1,
      dateShow: false,
      storeViewText: '请选择门店',
      errorType: ['message'],
      typeList: [
        {
          value: '1',
          label: '实物'
        },
        {
          value: '2',
          label: '优惠券'
        }
      ],
      beginDateShow: true,
      endDateShow: false,
      integralSet: '0',
      form: {
        id: '',
        coverImage: '',
        createStore: '',
        drawIntegral: '0',
        drawLimit: '1',
        drawNumber: '',
        drawRule: '',
        inventedJoinNumber: '',
        luckdrawTitle: '',
        shareImage: '',
        timeEnd: '',
        timeStart: '',
        useStores: '',
        luckdrawGsDtos: [
          // {
          // 	couponId: "",
          // 	couponName: "",
          // 	prizeName: "",
          // 	prizeNumber: "",
          // 	prizeProbability: "",
          // 	prizeType:''
          // }
        ]
      },
      useNoticeTxt: {
        show: true,
        mode: 'range',
        type: 'textarea',
        height: 100,
        autoHeight: true
      },
      rules: {
        luckdrawTitle: [
          {
            required: true,
            message: '请输入名称',
            trigger: ['blur', 'change']
          }
        ],
        timeStart: [
          {
            required: true,
            message: '请输入开始时间',
            trigger: ['blur', 'change']
          }
        ],
        timeEnd: [
          {
            required: true,
            message: '请输入结束时间',
            trigger: ['blur', 'change']
          }
        ],
        useStores: [
          {
            required: true,
            message: '请选择活动门店',
            trigger: ['blur', 'change']
          }
        ],
        drawNumber: [
          {
            required: true,
            message: '请输入抽奖次数',
            trigger: ['blur', 'change']
          }
        ],
        coverImage: [
          {
            required: true,
            message: '请选择活动封面',
            trigger: ['blur', 'change']
          }
        ],
        shareImage: [
          {
            required: true,
            message: '请选择分享封面',
            trigger: ['blur', 'change']
          }
        ],
        drawRule: [
          {
            required: true,
            message: '请输入活动内容',
            trigger: ['blur', 'change']
          }
        ]
      },
      prizeIndex: 0,
      prizeTypeText: [],
      timeType: '',
      initUseStores: ''
    };
  },
  computed: {
    ...mapGetters(['userInfo', 'selectStore']),
    surplus_prob() {
      return (100 - this.form.luckdrawGsDtos.reduce((pre, cur) => pre + Number(cur.prizeProbability), 0) * 100).toFixed(0);
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
    this.form.createStore = this.userInfo.storeBasicId;
    this.form.useStores = this.userInfo.storeBasicId;
    this.getDetail();
  },
  onShow() {
    if (this.selectStore.length) {
      var selStoreArr = [];
      this.selectStore.forEach((item, index) => {
        selStoreArr.push(item.storeId);
      });
      this.storeViewText = `已选${selStoreArr.length}家门店`;
      selStoreArr = selStoreArr.join();
      this.form.useStores = selStoreArr;
    }
    uni.$on('setCardData', data => {
      this.form.luckdrawGsDtos[data.pagelist].couponId = data.coupon[0].id;
      this.form.luckdrawGsDtos[data.pagelist].couponName = data.coupon[0].name;
	  this.form.luckdrawGsDtos[data.pagelist].sendTotalType = data.coupon[0].sendTotalType;
	  this.form.luckdrawGsDtos[data.pagelist].sendReceive = data.coupon[0].sendReceive;
    });
  },

  onLoad(options) {
    this.form.id = JSON.parse(options.param).id;
  },
  onUnload() {
    this.$store.commit('setSelectStore', []);
  },
  methods: {
    getDetail() {
      lotteryEditEcho({id: this.form.id}).then(res => {
        var data = res.data;

        this.form.coverImage = data.coverImage;
        this.fileList = [{url: this.$imagePath + data.coverImage}];
        this.form.shareImage = data.shareImage;
        this.fileList1 = [{url: this.$imagePath + data.shareImage}];
        this.form.createStore = data.createStore;
        this.form.drawIntegral = data.drawIntegral;
        if (data.drawIntegral > 0) {
          this.integralSet = 1;
        } else {
          this.integralSet = 0;
        }
        this.form.drawLimit = data.drawLimit;
        this.form.drawNumber = '' + data.drawNumber;
        this.form.drawRule = data.drawRule;
        this.form.inventedJoinNumber = data.inventedJoinNumber;
        this.form.luckdrawTitle = data.luckdrawTitle;

        this.form.timeEnd = data.timeEnd;
        this.form.timeStart = data.timeStart;
        this.form.useStores = data.useStores;
        this.initUseStores = data.useStores;
        if (data.useStores == this.userInfo.storeBasicId) {
          this.storeType = 0;
        } else {
          this.storeType = 1;
          // this.selectStore = data.useStores.split(',')
        }

        data.luckdrawGsEntities.forEach(item => {
          this.form.luckdrawGsDtos.push({
            couponId: item.couponId,
            couponName: item.couponName,

            prizeName: item.prizeName,
            prizeNumber: item.prizeNumber,
            prizeProbability: item.prizeProbability,
            prizeType: item.prizeType
          });
          this.prizeTypeText.push(this.typeList.filter(ite => ite.value == item.prizeType)[0].label);
        });
      });
    },
    radioChange(e) {
      if (e == 0) {
        this.form.useStores = this.userInfo.storeBasicId;
      }
      if (e == 1) {
        var selStoreArr = [];
        this.selectStore.forEach((item, index) => {
          selStoreArr.push(item.storeId);
        });
        // this.form.useStores=selStoreArr.length? selStoreArr : this.initUseStores
        // this.form.useStores=this.selectStore|| this.initUseStores
        this.form.useStores = this.selectStore.length ? selStoreArr.toLocaleString() : this.initUseStores;
        this.goselectStore();
      }
    },
    goselectStore() {
      this.$store.commit('setSelectStoreStr', this.form.useStores);
      this.$navigateTo('/pages/selectStore/selectStore', {});
    },
    delLuckdrawGsDtos(index) {
      if (this.form.luckdrawGsDtos.length <= 1) {
        uni.showToast({
          title: '不能删除了',
          icon: 'none'
        });
        return;
      }
      this.form.luckdrawGsDtos.splice(index, 1);
    },
    submit() {
      let that = this;
      if (this.integralSet == 1 && this.form.drawIntegral == 0) {
        uni.showToast({
          title: '请输入每次消耗积分',
          icon: 'none'
        });
        return;
      }
      if (this.surplus_prob < 0) {
        uni.showToast({
          title: '概率相加不能大于1',
          icon: 'none'
        });
        return;
      }
      // if(this.surplus_prob>0){
      // 	uni.showToast({
      // 		title:'概率相加不能小于1',
      // 		icon:'none',
      // 	})
      // 	return
      // }
      var boo = function () {
        var boo = true;
        that.form.luckdrawGsDtos.forEach((item, index) => {
          Object.keys(item).forEach(ite => {
            if (!item[ite] && ite != 'couponId' && ite != 'couponName' && ite != 'prizeProbability') {
              if (ite == 'prizeName') var str = '请输入奖品名称';
              if (ite == 'prizeNumber') var str = '请输入奖品库存数量';
              if (ite == 'prizeType') var str = '请输选择奖品类型';
              that.$refs.uToast.show({
                title: str,
                type: 'default'
              });
              boo = false;
            }
          });
		  if(!item.prizeProbability){
		  	item.prizeProbability = 0
		  }
          if (item.prizeType == 2 && !item.couponId && !item.couponName) {
            that.$refs.uToast.show({
              title: '请选择优惠券',
              type: 'default'
            });
            boo = false;
          }
		  if(item.sendTotalType == 2 && item.prizeNumber > item.sendReceive){
			  // 如果奖品数量上限增加  对应fthat.focus5 = false; 增加
			  that.focus0 = false;
			  that.focus1 = false;
			  that.focus2 = false;
			  that.focus3 = false;
			  that.focus4 = false;
			setTimeout(() => {
				that["focus"+index] = true
			},0)
			  that.$refs.uToast.show({
				title: '奖品库存大于优惠券剩余库存',
				type: 'default'
			  });
			  boo = false;
		  }
          // if( ite == 'prizeProbability' ) var str = '请输入中奖概率'
        });
        return boo;
      };
      if (!boo()) return;
      that.$refs.uForm.validate(valid => {
        if (valid) {
          lotteryEdit(that.form).then(res => {
            if (res.code == '1') {
              that.$refs.uToast.show({
                title: '编辑成功',
                type: 'success'
              });
              that.$put('isCreatStatus', '1');
              that.$store.commit('setSelectStore', []);
              uni.switchTab({
                url: '/pages/marketing/marketing'
              });
            } else {
              that.$refs.uToast.show({
                title: res.msg,
                type: 'default'
              });
            }
          });
        } else {
          console.log('验证失败');
        }
      });
    },
    opentype(index) {
      this.prizeIndex = index;
      this.typeShow = true;
    },
    selcoupon(index) {
      this.prizeIndex = index;
      uni.navigateTo({
        url: '/marketing/lottery/coupons?index=' + this.prizeIndex
      });
    },
    selTprizeTpe(e) {
      this.form.luckdrawGsDtos[this.prizeIndex].prizeType = e[0].value;
      this.prizeTypeText[this.prizeIndex] = e[0].label;
    },
    addLuckdrawGsDtos() {
      if (this.form.luckdrawGsDtos.length >= 5) {
        uni.showToast({
          title: '最多添加5个奖品',
          icon: 'none'
        });
        return;
      }
      this.form.luckdrawGsDtos.push({
        couponId: '',
        couponName: '',
        prizeName: '',
        prizeNumber: '',
        prizeProbability: '',
        prizeType: ''
      });
    },
    cancelmodal() {
      this.form.drawRule = '';
    },
    onSuccess(data, index, lists, name) {
      if (this.updatatype == 1) {
        this.form.coverImage = data.data.saveUrl;
      } else if (this.updatatype == 2) {
        this.form.shareImage = data.data.saveUrl;
      }
    },
    dateChange(e) {
      var arr1 = [e.year, e.month, e.day].join('-');
      var arr2 = [e.hour, e.minute, e.second].join(':');
      if (this.timeType == 0) {
        this.form.timeStart = arr1;
      } else if (this.timeType == 1) {
        this.form.timeEnd = arr1;
      }
    },
    integralSetFun(e) {
      if (e == 0) {
        this.form.drawIntegral = e;
      }
    },
    godetail() {
      if (this.form.luckdrawGsDtos.length <= 1) {
        uni.showToast({
          title: '请至少添加2个奖品',
          icon: 'none'
        });
        return;
      }
      uni.navigateTo({
        url: '/marketing/lottery/detail?goods=' + JSON.stringify(this.form.luckdrawGsDtos)
      });
    }
  }
};
</script>

<style lang="less" scoped>
.list {
  background-color: #fff;
  padding: 13rpx 40rpx;
  margin: 13rpx 22rpx;

  .title {
    font-size: 24rpx;
    line-height: 90rpx;

    .title_text {
      position: relative;
    }

    .title_text:after {
      position: absolute;
      width: 8rpx;
      top: 30rpx;
      height: 32rpx;
      content: '';
      left: -20rpx;
      border-radius: 20rpx;
      background-color: #007fff;
    }
  }

  .remark {
     font-size: 24rpx;
     color: #888888;
     line-height: 30rpx;
   }
}

.coupon_title {
  font-weight: 600;
  line-height: 60rpx;
}

.btn {
  margin: 50rpx 0;
}
</style>
